<?php
/**
 * Created by PhpStorm.
 * User: GuoHengxi
 * Date: 13-12-9
 * Time: 下午7:17
 */

class WeixinAction extends Action
{
    //接收微信验证和消息
    public function index()
    {
        if(isset($_GET["echostr"])){
            $echoStr = $_GET["echostr"]; //随机字符串
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $token = C('TOKEN');
            if ($this->checkSignature($signature,$token,$timestamp,$nonce)) {
                echo $echoStr;
                exit();
            } else {
                return false;
            }
        }else{
            /**
             * ToUserName	开发者微信号
             * FromUserName	 发送方帐号（一个OpenID）
             * CreateTime	 消息创建时间 （整型）
             * MsgId	 消息id，64位整型
             * */
            $postStr = file_get_contents("php://input");
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fu = (string)$postObj->FromUserName;
            //$tu = (string)$postObj->ToUserName;
            $msgId = (string)$postObj->MsgId;
            $MsgType = (string)$postObj->MsgType;
            $MsgDao = M('msg');

            $data['fromUser'] = $fu;
            $data['type'] = $MsgType;
            $data['msgId'] = $msgId;

            if($MsgType == 'text'){
                /**
                 * Content	 文本消息内容
                 * */
                $content = (string)$postObj->Content;

                $msgarr = explode('@',$content);
                $len = sizeof($msgarr);
                if($len>1){
                    $fromUserName = $msgarr[$len-1];
                    $data['fromUserName'] = $fromUserName;
                }
                
                $data['content'] = $content;
                $MsgDao->add($data);

            }else if($MsgType == 'image'){
                /**
                 * PicUrl	 图片链接
                 * MediaId	 图片消息媒体id，可以调用多媒体文件下载接口拉取数据。
                 * */
                $pic = (string)$postObj->PicUrl;
                $mediaId = (string)$postObj->MediaId;
                $data['pic'] = $pic;
                $data['mediaId'] = $mediaId;
                $MsgDao->add($data);
            }else if($MsgType == 'voice'){
                /**
                 * MediaId	 语音消息媒体id，可以调用多媒体文件下载接口拉取数据。
                 * Format	 语音格式，如amr，speex等
                 * */
                $format = (string)$postObj->Format;
                $mediaId = (string)$postObj->MediaId;
                $data['format'] = $format;
                $data['mediaId'] = $mediaId;
                $MsgDao->add($data);
            }else if($MsgType == 'video'){
                /**
                 * MediaId	 视频消息媒体id，可以调用多媒体文件下载接口拉取数据。
                 * ThumbMediaId	 视频消息缩略图的媒体id，可以调用多媒体文件下载接口拉取数据。
                 * */
                $thumb = (string)$postObj->ThumbMediaId;
                $mediaId = (string)$postObj->MediaId;
                $data['thumbId'] = $thumb;
                $data['mediaId'] = $mediaId;
                $MsgDao->add($data);
            }else if($MsgType == 'location'){
                /**
                 * Location_X	 地理位置维度
                 * Location_Y	 地理位置精度
                 * Scale	 地图缩放大小
                 * Label	 地理位置信息
                 */
                $x = (double)$postObj->Location_X;
                $y = (double)$postObj->Location_Y;
                $scale = (int)$postObj->Scale;
                $label = (string)$postObj->Label;
                $data['locationX'] = $x;
                $data['locationY'] = $y;
                $data['scale'] = $scale;
                $data['label'] = $label;
                $MsgDao->add($data);
            }else if($MsgType == 'link'){
                /**
                 * Title	 消息标题
                 * Description	 消息描述
                 * Url	 消息链接
                 * */
                $title = (string)$postObj->Title;
                $desc = (string)$postObj->Description;
                $url = (string)$postObj->Url;
                $data['title'] = $title;
                $data['description'] = $desc;
                $data['url'] = $url;
                $MsgDao->add($data);
            }
        }
    }

    private function checkSignature($signature,$token,$timestamp, $nonce)
    {
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    //AJAX
    public function next(){
        $lastId = I('lastId');
        $partyId = I('partyId');
        if($partyId == null || $partyId == 'null'){
            echo 'Need Party Id.';
            exit();
        }
        $lastId = $lastId!=null ? $lastId : 0;
        try{
            $msgDao = M('msg');
            $where['id'] = array('gt',$lastId);
            $where['fromUserName'] = array('neq','');

            $party = M('party')->where(array('id'=>$partyId))->find();
            if($party!=null){
                $where['createTime'] = array('between',array($party['begin'],$party['end']));
                
                // $sql = "select * from __TABLE__ where id>".$lastId." and createTime > '".$party['begin']."' and createTime < '".$party['end']."' ORDER BY id asc LIMIT 1 ";
                // $msg = $msgDao->query($sql);
                $msg = $msgDao->where($where)->order('id asc')->find();

                //echo $msgDao->getLastSql();
                $this->ajaxReturn($msg);
            }
            $this->ajaxReturn(null);            
        }catch(Exception $e){
            echo $e;
            exit();
        }
    }
    //通过AJAX获取
    public function get(){
        $page = I('page');
        $limit = I('limit');
        $page = $page<=0?1:$page;
        $msgDao = M('msg');

        $total = $msgDao->count();
        $rs = $msgDao->order('createTime desc')->limit($limit*($page-1),$limit)->select();
        $data['total'] = $total;
        $data['rs'] = $rs;
        $this->ajaxReturn($data);
    }
    //删除 AJAX POST 方法
    public function delete(){
        $user = session('user');
        if($user==null){
            echo 'You have no permission to do this.';
            exit();
        }
        if($this->isGet()){
            echo 'Sorry illegal request method.';
            exit();
        }
        $id = I('id');
        $msgDao = M('msg');

        $rs = $msgDao->where(array('id'=>$id))->delete();
        if($rs){
            $this->ajaxReturn(null);
        }else{
            echo '删除失败';
            exit();
        }
    }
    //获取指定时间段的微信,Ajax
    public function users(){
        $begin = I('begin');
        if($begin==null || $begin=='' || $begin=='null'){
            echo '请输入开始时间';
            exit();
        }

        $dao = M('msg');

        $rs = $dao->where(
                    array(
                        'fromUserName'=>array('exp','is not null'),
                        'fromUserName'=>array('neq',''),
                        'createTime'=>array('gt',$begin)
                    )
                )
                ->field('fromUserName')
                ->group('fromUserName')
                //->group('fromUser')
                ->select();
        $arr = array();
        foreach ($rs as $key => $value) {
            $arr[] = $value['fromUserName'];
        }
        $this->ajaxReturn($arr);
    }
}